package com.own.component.common.util;

import lombok.Cleanup;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * Base64Util
 *
 * @author chenxueli
 * @date 2021/4/14 20:23
 */
public final class Base64Util {

    /**
     * 图片转换Base64的方法
     *
     * @param path 图片地址
     * @return base64代码
     */
    public static String imageToBase64(String path) {
        return FormUtil.isUrl(path) ? netImageToBase64(path) : pathImageToBase64(path);
    }

    /**
     * 网络图片转换Base64的方法
     *
     * @param path 图片地址
     * @return base64代码
     */
    public static String netImageToBase64(String path) {
        var stream = new ByteArrayOutputStream();
        try {
            var url = new URL(path);
            var by = new byte[1024];
            var connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            @Cleanup
            var inputStream = connection.getInputStream();
            int len;
            while ((len = inputStream.read(by)) != -1) {
                stream.write(by, 0, len);
            }
            return org.apache.commons.codec.binary.Base64.encodeBase64String(stream.toByteArray());
        } catch (IOException e) {
            return "";
        }
    }


    /**
     * 本地图片转换Base64的方法
     *
     * @param path 图片路径
     * @return base64代码
     */
    @SuppressWarnings("all")
    public static String pathImageToBase64(String path) {
        byte[] data = null;
        try {
            @Cleanup
            var inputStream = new FileInputStream(path);
            data = new byte[inputStream.available()];
            inputStream.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(data);
    }

}
